<?php

namespace app\user\controller\mall\user;

use app\common\controller\Userend;

/**
 * 用户地址
 *
 * @icon fa fa-circle-o
 */
class Address extends Userend
{
    
    /**
     * Address模型对象
     * @var \app\common\model\mall\user\Address
     */
    protected $model = null;
    protected $noNeedRight = ['getById','listQuery'];
    /**
     * Multi方法可批量修改的字段
     */
    protected $multiFields = 'isDefault';
    
    public function _initialize()
    {
        parent::_initialize();
        $exist = \think\Db::query("show tables like'".config('database.prefix')."area'");
        if(!$exist) $this->error("地区数据不存在，请安装<a href=\"https://www.fastadmin.net/store/example.html\" target=\"_blank\">[开发示例]</a>插件！");
        $this->model = new \app\common\model\mall\user\Address;

    }
        
    /**
     * 批量更新
     */
    public function multi($ids = "")
    {        
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids){
            $idArray = explode(",",$ids);
            if(count($idArray)>1) $this->error("您选择了多个记录，设置默认地址只能选择一条记录！");
            if ($this->request->has('params')){
                $values = [];
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values)
                {
                    $user_ids = $this->getDataLimitUserIds();
                    if (is_array($user_ids)){
                        $this->model->where($this->dataLimitField, 'in', $user_ids);
                    }
                    $count=0;
                    $count =$this->model->where($this->model->getPk(), $ids)->update($values);//更新当前记录为默认值成功
                    /*$list = $this->model->where($this->model->getPk(),$ids)->select();
                    foreach ($list as $item) {
                        $count += $item->allowField(true)->isUpdate(true)->save($values);
                    }*/
                    if ($count==1){
                        if($values['isDefault']){
                            //更新其它记录为非默认值
                            $this->model->where( [ "id"=>['<>',$ids],'user_id'=>$this->auth->id] )->setField('isDefault',0);
                        }
                        $this->success();
                    }else{
                        $this->error(__('No rows were updated'));
                    }
                }else{
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 获取用户地址
     */
    public function getById(){        
        $id=(int)input('id');
        $data = $this->model->getById($id);
        $this->success('', "",$data);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where(['user_id'=>$this->auth->id,'status'=>'normal'])
                ->order('isDefault desc, id desc')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where(['user_id'=>$this->auth->id,'status'=>'normal'])
                ->order('isDefault desc, id desc')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                if ($this->dataLimit && $this->dataLimitFieldAutoFill){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = $this->modelSceneValidate ? $name . '.add' : $name;
                        $result = $this->validate($params,$validate);
                        if(true !== $result){
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false){
                        //修改默认地址
                        if((int)$params['isDefault']==1)
                            $this->model->where(["id"=>["<>",$this->model['id']],"user_id"=>$this->auth->id])->setField('isDefault',0);
                        $this->success();
                    }else{
                        $this->error($this->model->getError());
                    }
                }catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑资料
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $user_ids = $this->getDataLimitUserIds();
        if (is_array($user_ids))
        {
            if (!in_array($row[$this->dataLimitField], $user_ids))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params){
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = $this->modelSceneValidate ? $name . '.edit' : $name;
                        $result = $this->validate($params,$validate);
                        if(true !== $result){
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false){
                        //修改默认地址
                        if((int)$params['isDefault']==1)
                            $this->model->where(["id"=>["<>",$row['id']],"user_id"=>$this->auth->id])->setField('isDefault',0);
                        $this->success();
                    }else{
                        $this->error($row->getError());
                    }
                }catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
